//
//  LSCustomView.m
//  CROSBY
//
//  Created by Harvey on 2018/3/27.
//  Copyright © 2018年 Haley. All rights reserved.
//

#import "LSCustomView.h"

@interface LSCustomView()

@property (strong, nonatomic) NSMutableArray            *squareViews;

@end

@implementation LSCustomView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _rows = kGraffiRows;
        _cols = kGraffiCols;
        [self initSubView];
        [self initData];
    }
    return self;
}

- (NSMutableArray *)squareViews
{
    if (!_squareViews) {
        _squareViews = [[NSMutableArray alloc] init];
    }
    return _squareViews;
}

- (void)initSubView
{
    for (int i = 0; i < self.cols; i++) {
        NSMutableArray *colsArray = [[NSMutableArray alloc] init];
        for (int j = 0; j < self.rows; j++) {
            UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
            [self addSubview:view];
            [colsArray addObject:view];
        }
        [self.squareViews addObject:colsArray];
    }
}

- (void)initData
{
    NSMutableArray *data = [NSMutableArray array];
    for (int i = 0; i < self.cols; i++) {
        NSMutableArray *colsArray = [[NSMutableArray alloc] init];
        for (int j = 0; j < self.rows; j++) {
            [colsArray addObject:@(NO)];
        }
        [data addObject:colsArray];
    }
    _data = [data copy];
}

- (void)setData:(NSArray *)data
{
    _data = data;
    
    for (int i = 0; i < data.count; i++) {
        NSArray *array = [data objectAtIndex:i];
        for (int j = 0; j < array.count; j++) {
            NSNumber *number = [array objectAtIndex:j];
            UIView *view = self.squareViews[i][j];
            if (number.boolValue) {
                view.backgroundColor =  RGBColor(251, 0, 195, 1);
            } else {
                view.backgroundColor = [UIColor lightGrayColor];
            }
        }
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    CGFloat sW = (self.bounds.size.width - 3 * (self.cols + 1)) / self.cols;
    CGFloat sH = sW;

    for (int i = 0; i < self.cols; i++) {
        for (int j = 0; j < self.rows; j++) {
            CGFloat sX = 3 + (3 + sW) * i;
            CGFloat sY = 3 + (3 + sW) * j;
            UIView *view = self.squareViews[i][j];
            view.layer.borderColor = [UIColor grayColor].CGColor;
            view.layer.borderWidth = 0.5;
            view.frame = CGRectMake(sX, sY, sW, sH);
        }
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
